# -*- coding: UTF-8 -*-
import bwt
import sys, time

if __name__ == "__main__":
    # 数据准备
    Matches = []
    test = ''
    origin = ''
    Template = open('Template/NC_008253.fna')
    Match1 = open('Matches/Ecoli_4x.fq1')
    Match2 = open('Matches/Ecoli_4x.fq2')
    head = Template.readline()
    linesOfMatch1 = Match1.readlines()
    linesOfMatch2 = Match2.readlines()
    num1 = len(linesOfMatch1) / 4
    num2 = len(linesOfMatch2) / 4
    for i in range(0, num1):
        Matches += [linesOfMatch1[4 * i + 1].split('\n')[0]]
    for i in range(0, num2):
        Matches += [linesOfMatch2[4 * i + 1].split('\n')[0]]

    # 选取要匹配的序列
    print 'Number of sequences to be matched: ' + str(num1 + num2)
    print 'Input serial number of the sequence that you want to match(0 ~ ' + str(num1 + num2) + '): '
    choice = input()
    test = Matches[choice]
    # 设置miss match的阈值
    print 'Input threshold of miss matches: '
    miss = input()
    Found = False
    # 总数据500万数据量太大，每1万左右的数据量进行匹配
    for i in range(0, 471):
        content = ''
        bar = '|'
        if i == 470:
            temp = Template.readlines()
            for j in range(0, len(temp)):
                content += temp[j].split('\n')[0]
        else:
            for j in range(0, 150):
                content += Template.readline().split('\n')[0]
        bwt_data = bwt.make_all(content)
        result = bwt.find(test, content, miss, bwt_data)
        if len(result) > 0:
            Found = True
            for j in range(0, 70):
                origin += content[result[0]+j]
            for a in range(0, 100):
                bar += '#'
            bar += '|\r'
            sys.stdout.write(bar)
            sys.stdout.flush()
            break
        ratio = float(i) / 470 * 100
        for a in range(0, 100):
            if a <= int(ratio):
                bar += '#'
            else:
                bar += ' '
        bar += '|\r'
        sys.stdout.write(bar)
        sys.stdout.flush()
    print '\n'
    if Found == True:
        print 'Successfully match the sequence!'
        print 'Sequence: '
        print test
        print 'Match: '
        print origin
    else:
        print 'Fail to match the sequence.'